package com.peng.leetcode.tree;

import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.Set;

/**
 * IsCousins
 * 993. 二叉树的堂兄弟节点
 * https://leetcode.cn/problems/cousins-in-binary-tree/
 * <p>
 * Created on 2022/12/7
 *
 * @author lupeng
 */
public class IsCousins {
    public boolean isCousins(TreeNode root, int x, int y) {
        if (root == null) {
            return false;
        }
        Map<Integer, Integer> parentMap = new HashMap<>();
        Queue<TreeNode> q = new ArrayDeque<>();
        q.offer(root);
        while (!q.isEmpty()) {
            Set<Integer> currLevelValSet = new HashSet<>();
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode n = q.poll();
                currLevelValSet.add(n.val);
                if (n.left != null) {
                    q.offer(n.left);
                    parentMap.put(n.left.val, n.val);
                }
                if (n.right != null) {
                    q.offer(n.right);
                    parentMap.put(n.right.val, n.val);
                }
            }
            if (currLevelValSet.contains(x) && currLevelValSet.contains(y)
                    && !Objects.equals(parentMap.get(x), parentMap.get(y))) {
                return true;
            }
        }
        return false;
    }
}
